module namespace merchandising = "http://www.xmlproject.com/smi/merchandising";

import module namespace http = "http://www.28msec.com/modules/http";
import module namespace findmerchandising = "http://www.xmlproject.com/smi/lib/controller/findmerchandising";
import module namespace merchandisingview = "http://www.xmlproject.com/smi/lib/view/merchandisingview";


declare sequential function merchandising:showItems() {
    declare $query as xs:string := if(empty(http:get-parameters("query")[1]))
                                   then ""
                                   else xs:string(http:get-parameters("query")[1]);
                                   
    declare $title as xs:string := if(empty(http:get-parameters("title")[1]))
                                   then ""
                                   else xs:string(http:get-parameters("title")[1]);
                                   
    (: make sure query is not empty :)
    if ($query = "")
    then 
        block
        {
            
            (: signal Bad Request Error :)
            http:set-status(400);
            
            (: with the content-type "application/json" the json xml is automatically 
               serialized to valid JSON :)
            http:set-content-type("application/json");
            
            (: this is the xml representation of JSON which makes it easy to generate it, 
               and work with it within sausalito :)
            <json type="object">
                <pair name="status" type="number">400</pair>
                <pair name="statusmessage" type="string">Bad Request</pair>
                <pair name="message" type="string">Please, enter a search term</pair>
            </json>;
        }
    else 
        block
        {
            (: browsers should not cache the results :)
            http:set-header("Cache-Control", "no-cache"),
            
            (: with the content type "application/jsonml+json" sausalito
               automatically serializes any xml to jsonml :)
            http:set-content-type("text/html");
    
            let $merchandisingResults := findmerchandising:search($title, $query)

            (: get the HTML result table for the results :)
            return            
                merchandisingview:show($merchandisingResults);              
        }
};